//
//  TSCMyToast.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-19.
//  Copyright (c) 2015年 idream. All rights reserved.
//
// -- TODO 字数太多将无法显示

#define TOAST_APPEAR_DISAPPEAR_SECOND 0.5f // 淡入、淡出的时间（秒）
#define TOAST_TEXT_PADDING 15.0f // toast距离屏幕的padding

#import "TSCMyToast.h"
#import "TSCConstants.h"
#import "TSCMyUIUtil.h"

@implementation TSCMyToast {
    NSMutableArray * _allWindowConstraintShouldBeRecycled; // 创建toast时添加到
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/**
 * 像安卓toast一样显示
 *
 * @date 2015-05-19
 * @author Rio
 */
+ (void)makeTextWithResourceKey:(NSString *)resourceKey ti:(NSTimeInterval)ti {
    [self makeTextWithString:NSLocalizedString(resourceKey, nil) ti:ti];
}

/**
 * 像安卓toast一样显示
 *
 * @date 2015-05-19
 * @author Rio
 */
+ (void)makeTextWithString:(NSString *)string ti:(NSTimeInterval)ti {
    // 创建并显示toast
    UIView * toast = [self createAndAddToastWithString:string];
    
    // 先设置为透明
    toast.alpha = 0.0f;
    
    // 动画显示
    [UIView animateWithDuration:TOAST_APPEAR_DISAPPEAR_SECOND animations:^{
        toast.alpha = 1.0f;
    } completion:^(BOOL finished) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 等待自动关闭
            [NSThread sleepForTimeInterval:ti];
            
            // 自动关闭
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:TOAST_APPEAR_DISAPPEAR_SECOND animations:^{
                    toast.alpha = 0.0;
                } completion:^(BOOL finished) {
                    // 从主窗体移除
                    [toast removeFromSuperview];
                    
                    // 注：根据这篇文章，当view A从父view F移除时，F中保存的所有关于A的约束，都将被删除，所以不用手工删除这些约束了
                    // http://stackoverflow.com/questions/18617991/what-happens-with-constraints-when-a-view-is-removed
                }];
            });
        });
    }];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

/* private */ + (UIView *) createAndAddToastWithString:(NSString *)string {
    // 方法一：通过frame来计算label、toast的宽高（已废弃）
    //    // 初始化toast、label的宽高
    //    UIFont * labelFont = [TSCMyUIUtil getSystemDefaultFont];
    //    CGFloat toastW = UI_SCREEN_WIDTH - UI_SCREEN_PADDING * 2; // 宽 == 屏幕宽度的3/4
    //    CGFloat toastH = 0; // 后续重新计算
    //    CGFloat labelW = toastW - TEXT_PADDING * 2;
    //    CGFloat labelH = 0; // 后续重新计算
    //
    //    // 在限定宽度、字数的情况下，计算label的实际高度
    //    CGSize labelSize = [string boundingRectWithSize:CGSizeMake(labelW, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName: labelFont} context:nil].size;
    //    labelH = labelSize.height;
    //    // 同时调整toast高度
    //    toastH = labelH + TEXT_PADDING * 2;
    
    // 方法二：通过约束控制label、toast的位置、大小
    
    // 设置toast
    UIView * vToast = [[UIView alloc]init];
    vToast.backgroundColor = COLOR_MT_TOAST_BG;
    [TSCMyUIUtil setUIRoundRectBG:vToast radius:5.0]; // toast圆角
    UIWindow * win = [[UIApplication sharedApplication].delegate window];
    [win addSubview:vToast]; // 将toast立即添加到window（因为后续要设置约束）
    
    // 创建label
    UILabel * lbText = [[UILabel alloc]init];
    lbText.font = [TSCMyUIUtil getSystemDefaultFont];
    lbText.text = string;
    lbText.textAlignment = NSTextAlignmentCenter;
    lbText.textColor = COLOR_MT_TOAST_TEXT;
    lbText.numberOfLines = 0; // 不限制行数
    [vToast addSubview:lbText];
    
    // 约束
    // label
    lbText.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%f-[lbText]-%f-|", TOAST_TEXT_PADDING, TOAST_TEXT_PADDING] options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbText)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[lbText]-%f-|", TOAST_TEXT_PADDING, TOAST_TEXT_PADDING] options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbText)]];
    // toast
    vToast.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%f-[vToast]-%f-|", UI_SCREEN_PADDING, UI_SCREEN_PADDING] options:0 metrics:nil views:NSDictionaryOfVariableBindings(vToast)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[vToast]-%f-|", UI_SCREEN_PADDING] options:0 metrics:nil views:NSDictionaryOfVariableBindings(vToast)]];
    
    return vToast;
}

@end
